<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="项目标段" prop="institutionCode">
        <el-select
          v-model="queryParams.institutionCode"
          placeholder="请选择"
          size="small"
          style="width: 240px" @change="handleBidChange"
        >
          <el-option-group
            v-for="group in bidOptions"
            :key="group.name"
            :label="group.name">
            <el-option
              v-for="item in group.bids"
              :key="item.code"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-option-group>
        </el-select>
      </el-form-item>

      <el-form-item label="清单编码" prop="boqCode">
        <el-input
          v-model="queryParams.boqCode"
          placeholder="请输入清单编码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="清单名称" prop="boqName">
        <el-input
          v-model="queryParams.boqName"
          placeholder="请输入清单名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="清单类型" prop="meterageBoqType">
        <el-select
          v-model="queryParams.meterageBoqType"
          placeholder="请选择"
          size="small"
          style="width: 240px"
          @change="handleBidChange"
        >
          <el-option
            v-for="item in meterageTypeOptions"
            :key="item.value"
            :value="item.value"
            :label="item.label"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['project:meterage:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['project:meterage:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['project:meterage:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleClean"
          v-hasPermi="['project:meterage:remove']"
        >清空</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleGenerate"
          v-hasPermi="['project:boq:add']"
        >生成</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['project:boq:import']"
        >导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="meterageList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="清单编号" align="left" prop="boqCode" width="100" />
      <el-table-column label="清单名称" align="left" prop="boqName" width="200" show-overflow-tooltip />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="起始桩号" align="center" prop="beginStation" />
      <el-table-column label="截止桩号" align="center" prop="endStation" />
      <el-table-column label="单价" align="center" prop="price" />
      <el-table-column label="是否完成" align="center" prop="complete" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.complete"/>
        </template>
      </el-table-column>
      <el-table-column label="数量" align="center" prop="amount" />
      <el-table-column label="已计量数量" align="center" prop="alreadyAmount" />
      <el-table-column label="剩余数量" align="center" prop="remainderAmount" />
      <el-table-column label="金额" align="center" prop="total" />
      <el-table-column label="已计量金额" align="center" prop="alreadyTotal" />
      <el-table-column label="剩余金额" align="center" prop="remainderTotal" />
      <el-table-column label="清单类型" align="center" prop="meterageBoqType">
        <template slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.meterageBoqType == '0'">合同</el-tag>
          <el-tag size="mini" type="danger" v-if="scope.row.meterageBoqType == '1'">变更</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="显示排序" align="center" prop="orderNum" />
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改计量清单对话框 -->
    <el-dialog :title="title" :visible.sync="open" :close-on-click-modal="false" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="清单名称" prop="institutionBoqCode">
          <el-select v-model="form.institutionBoqCode" filterable placeholder="请选择清单" style="width: 100%">
            <el-option
              v-for="item in boqOptions"
              :key="item.institutionBoqCode"
              :label="item.boqName"
              :value="item.institutionBoqCode">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="起始桩号" prop="beginStation">
          <el-input v-model="form.beginStation" placeholder="请输入起始桩号" />
        </el-form-item>
        <el-form-item label="截止桩号" prop="endStation">
          <el-input v-model="form.endStation" placeholder="请输入截止桩号" />
        </el-form-item>
        <el-form-item label="分　　部" prop="place">
          <el-input v-model="form.place" placeholder="请输入分部" />
        </el-form-item>
        <el-form-item label="分　　项" prop="item">
          <el-input v-model="form.item" placeholder="请输入分项" />
        </el-form-item>
        <el-form-item label="数　　量" prop="amount">
          <el-input v-model="form.amount" type="number" @keydown.native="handleKey" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="排　　序" prop="orderNum">
          <el-input v-model="form.orderNum" type="number" @keydown.native="handleKey" placeholder="请输入显示排序" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 计量导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?institutionCode=' + this.queryParams.institutionCode + '&updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
           <el-checkbox v-model="upload.updateSupport" /> 数据续导 <el-tooltip class="item" effect="light" content="如果不勾选，将会先删除所有计量清单" placement="top-start"><span><i class="el-icon-question"></i></span></el-tooltip>
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 生成清单对话框 -->
    <el-dialog :title="gen.title" :visible.sync="gen.open" width="400px" style="top: 20%" append-to-body>
      <h4 class="text-danger" style="margin-top: 0px;">
        1.生成计量清单功能将会删除原有计量清单数据。
      </h4>
      <h4 class="text-danger">
        2.如果原有计量清单已参与计量，将无法进行生成操作。
      </h4>
      <el-select v-model="gen.bigTypeValue" multiple collapse-tags placeholder="请选择清单大类" style="width: 100%">
        <el-option
          v-for="item in gen.bigTypeBoqOptions"
          :key="item.boqCode"
          :label="item.boqName"
          :value="item.boqCode">
        </el-option>
      </el-select>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitGenForm">确 定</el-button>
        <el-button @click="cancelGen">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listMeterage, getMeterage, delMeterage, addMeterage, updateMeterage, generateMeterage, importTemplate, beforeImportValidate, clean } from "@/api/project/meterage";
import { listBidBoq, selectBigTypeList} from "@/api/project/boq";
import {selectProjectBidBranch, selectProjectBidOrBranch} from "@/api/project/bid";
import {getToken} from "@/utils/auth";

export default {
  name: "Meterage",
  dicts: ['sys_yes_no'],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 导出遮罩层
      exportLoading: false,
      // 标段下拉框
      bidOptions: [],
      // 清单类型下拉框
      meterageTypeOptions: [{
        value: "0",
        label: "合同"
      },{
        value: "1",
        label: "变更"
      }],
      // 清单下拉框
      boqOptions: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 计量清单表格数据
      meterageList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        institutionCode: null,
        boqCode: null,
        boqName: null,
        meterageBoqType: null
      },
      // 清单导入参数
      upload: {
        // 是否显示弹出层（清单导入）
        open: false,
        // 弹出层标题（清单导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的清单数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { token: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/project/meterage/importData"
      },
      // 计量清单生成参数
      gen: {
        // 选择的清单大类
        bigTypeValue: [],
        // 清单大类列表
        bigTypeBoqOptions: [],
        // 是否显示弹出层（计量清单生成）
        open: false,
        // 弹出层标题（计量清单生成）
        title: ""
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        institutionBoqCode: [
          { required: true, message: "清单名称不能为空", trigger: "blur" }
        ],
        beginStation: [
          // {pattern: /^K[0-9]+/, message: "起始桩号格式不正确", trigger: "blur"},
          { required: true, message: "起始桩号不能为空", trigger: "blur" }
        ],
        endStation: [
          // {pattern: /^K[0-9]+/, message: "终止桩号格式不正确", trigger: "blur"},
          { required: true, message: "终止桩号不能为空", trigger: "blur" }
        ],
        amount: [
          { required: true, message: "数量不能为空", trigger: "blur" }
        ],
        orderNum: [
          { required: true, message: "排序不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.initBidSelect();
  },
  methods: {
    /** 初始化标段下拉框 */
    initBidSelect() {
      selectProjectBidOrBranch().then(response => {
        this.queryParams.institutionCode = this.$route.query.institutionCode;
        this.bidOptions = response.data;
        this.getList();
      });
    },
    /** 查询计量清单列表 */
    getList() {
      this.loading = true;
      listMeterage(this.queryParams).then(response => {
        this.meterageList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        meterageBoqId: null,
        institutionCode: null,
        institutionBoqCode: null,
        boqCode: null,
        boqName: null,
        ancestors: null,
        orderNum: null,
        unit: null,
        price: null,
        amount: null,
        total: null,
        remainderAmount: null,
        remainderTotal: null,
        alreadyAmount: null,
        alreadyTotal: null,
        replayAmount: null,
        replayTotal: null,
        complete: null,
        place: null,
        item: null,
        beginStation: null,
        endStation: null,
        changeOrderNo: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.institutionCode = this.$route.query.institutionCode;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.meterageBoqId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    // 标段下拉框发生变化
    handleBidChange() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 新增按钮操作 */
    handleAdd() {
      if (this.queryParams.institutionCode == null) {
        this.$modal.msgError("请选择项目标段");
        return;
      }
      listBidBoq({institutionCode: this.queryParams.institutionCode}).then(response => {
        this.boqOptions = response.data;
        this.reset();
        this.open = true;
        this.title = "添加计量清单";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      if (this.queryParams.institutionCode == null) {
        this.$modal.msgError("请先选择项目标段");
        return;
      }
      this.reset();
      const meterageBoqId = row.meterageBoqId || this.ids
      getMeterage(meterageBoqId).then(response => {
        this.form = response.data;
        listBidBoq({institutionCode: this.queryParams.institutionCode}).then(response => {
          this.boqOptions = response.data;
          this.open = true;
          this.title = "修改计量清单";
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        this.form.institutionCode = this.queryParams.institutionCode;
        if (valid) {
          if (this.form.meterageBoqId != null) {
            updateMeterage(this.form).then(response => {
              this.$modal.msgSuccess("操作成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMeterage(this.form).then(response => {
              this.$modal.msgSuccess("操作成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const meterageBoqIds = row.meterageBoqId || this.ids;
      this.$modal.confirm('确认删除选中的数据项？').then(function() {
        return delMeterage(meterageBoqIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => {});
    },
    /** 清空按钮操作 */
    handleClean() {
      if (this.queryParams.institutionCode == null) {
        this.$modal.msgError("请先选择项目标段");
        return;
      }
      this.$modal.confirm('确认清空该标段下所有计量清单数据？').then(() => {
        return clean({ institutionCode: this.queryParams.institutionCode});
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => {});
    },
    /** 生成按钮操作 */
    handleGenerate() {
      if (this.queryParams.institutionCode == null) {
        this.$modal.msgError("请先选择项目标段");
        return;
      }
      // 获取清单大类
      selectBigTypeList({institutionCode: this.queryParams.institutionCode}).then(response => {
        this.gen.bigTypeBoqOptions = response.data;
        this.gen.open = true;
        this.gen.title = "生成计量清单";
      });
    },
    // 生成按钮提交操作
    submitGenForm() {
      if (this.gen.bigTypeValue.length == 0) {
        this.$modal.msgError("请选择要生成的清单大类");
        return;
      }
      let bigTypeValue = '';
      this.gen.bigTypeValue.forEach((item) => {
        bigTypeValue += item + ',';
      })
      bigTypeValue = bigTypeValue.substring(0, bigTypeValue.length - 1);
      generateMeterage({ institutionCode: this.queryParams.institutionCode, bigTypeValue: bigTypeValue}).then(response => {
        this.$modal.msgSuccess("操作成功");
        this.gen.bigTypeBoqOptions = [];
        this.gen.bigTypeValue = [];
        this.gen.open = false;
        this.getList();
      })
    },
    // 生成按钮取消操作
    cancelGen() {
      this.gen.bigTypeBoqOptions = [];
      this.gen.bigTypeValue = [];
      this.gen.open = false;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.$download.name(response.msg);
      });
    },
    /** 导入按钮操作 */
    handleImport() {
      if (this.queryParams.institutionCode == null) {
        this.$modal.msgError("请先选择项目标段");
        return;
      }
      // 导入前先验证
      beforeImportValidate({ institutionCode: this.queryParams.institutionCode}).then(response => {
        this.upload.title = "导入计量清单";
        this.upload.open = true;
      })
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.$modal.closeLoading();
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true, customClass: "myMessageBox" });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$modal.loading("正在导入数据，请稍后...");
      this.$refs.upload.submit();
    },
    handleKey(e) {
      let key = e.key
      // 不允许输入'e'和'.'
      if (key === 'e') {
        e.returnValue = false
        return false
      }
      return true
    },
  }
};
</script>

<style lang="scss">
  input::-webkit-outer-spin-button,
  input::-webkit-inner-spin-button {
    -webkit-appearance: none;
  }
  input[type='number'] {
    -moz-appearance: textfield;
  }
</style>
